<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sa="http://www.w3.org/1999/xhtml" lang="">
<head>
    <meta charset="utf-8">
    <title>邮件管理</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">邮件主题</label>
                    <div class="layui-input-inline">
                        <input id="subject" type="text" name="subject" placeholder="请输入邮件主题" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <button class="layui-btn layui-btn-md " lay-submit lay-filter="email-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-md" id="resetBtn">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="email-table" lay-filter="email-table"></table>
    </div>
</div>
<form id="ID-test-layer-wrapper" style="display: none;" class="layui-form" lay-filter="test">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item" id="sendDate">
                <label class="layui-form-label">发布日期</label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input" name="sendDate" autocomplete="off"
                           id="ID-laydate-type-datetime"
                           placeholder="yyyy-MM-dd HH:mm:ss">
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn  layui-btn-sm" lay-submit lay-filter="check-save"
                    id="check_save">
                <i class="layui-icon layui-icon-ok"></i>
                发送
            </button>
        </div>
    </div>
</form>
<script type="text/html" id="email-toolbar">
    <button class="layui-btn  layui-btn-md" lay-event="add" sa:hasPermission="email_add">
        <i class="layui-icon layui-icon-add-1"></i>
        新增
    </button>
</script>

<script type="text/html" id="email-bar">
    <button class="layui-btn layui-bg-blue layui-btn-sm" lay-event="sending">
        发送
    </button>
    <button class="layui-btn layui-bg-orange layui-btn-sm" lay-event="scheduleSend">
        <span>定时发送</span>
    </button>
    <button class="layui-btn  layui-btn-sm" lay-event="edit" sa:hasPermission="email_edit">
        <i class="layui-icon layui-icon-edit"></i>
    </button>
    <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="remove" sa:hasPermission="email_delete">
        <i class="layui-icon layui-icon-delete"></i>
    </button>
</script>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/layui/layarea.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">
    layui.use(['table', 'form', 'jquery', 'laydate', 'util'], function () {
        let baseURL = /*[[@{/}]]*/ '';
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let laydate = layui.laydate;
        let util = layui.util;
        let cols = [
            [
                {checkbox: true},
                {title: '邮件ID', field: 'id', maxWidth: 80, align: 'center',},
                {title: '邮件主题', field: 'subject', align: 'left',},
                {
                    title: '邮件状态',
                    field: 'status',
                    maxWidth: 100,
                    sort: true,
                    align: "center",
                    templet: function (d) {
                        const statusMap = {
                            0: "草稿",
                            1: "待发送",
                            2: "正在发送",
                            3: "已发送",
                        };
                        let statusText = statusMap[d.status] || "error";
                        return '<span>' + statusText + '</span>'
                    }
                },
                {title: '发送时间', field: 'sendTime', align: 'center'},
                {
                    title: '成功', field: 'successNum', align: 'center', maxWidth: 150,
                    templet: function (d) {
                        return '<span lay-event="viewSuccess" style="cursor: pointer" ><span style="color: #36B368;font-weight: bold">' + d.successNum + '</span>'
                    }
                },
                {
                    title: '失败', field: 'failNum', align: 'center', maxWidth: 150,
                    templet: function (d) {
                        return '<span lay-event="viewFail" style="cursor: pointer" ><span style="color: #FF5722;font-weight: bold">' + d.failNum + '</span>'
                    }
                },
                {
                    title: "已发送数量", field: 'count', align: "center",
                    templet: function (d) {
                        return '<span><span style="color: #36B368;font-weight: bold">' + d.count + '</span>&nbsp;/&nbsp;<span style="color: #1E9FFF;font-weight: bold">' + d.recipientNum + '</span>'
                    }
                },
                {title: '操作', toolbar: '#email-bar', align: 'center', width: 350}
            ]
        ]

        table.render({
            elem: '#email-table',
            url: baseURL + 'cms/email/list',
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            type: 'get',
            page: true,
            skin: 'line',
            curr: 1,
            cols: cols,
            toolbar: '#email-toolbar',
            limits: [5, 10, 15, 20],
            parseData: function (res) {// 对从后端获得的数据进行规范，最后返回四个键值对
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total,
                    "data": res.data.list, //解析数据列表
                };
            },
            response: {
                statusName: "code",
                msgName: "msg",
                statusCode: 1000,
                dataName: "data"
            },
        });

        table.on('tool(email-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj);
            } else if (obj.event === 'sending') {
                window.sending(obj);
            } else if (obj.event === 'scheduleSend') {
                window.scheduleSend(obj);
            } else if (obj.event === 'viewSuccess') {
                window.viewSuccess(obj);
            } else if (obj.event === 'viewFail') {
                window.viewFail(obj);
            }
        });

        table.on('toolbar(email-table)', function (obj) {
            if (obj.event === 'add') {
                window.add();
            } else if (obj.event === 'refresh') {
                window.refresh();
            }
        });

        form.on('submit(email-query)', function (data) {
            table.reload('email-table', {
                page: {
                    curr: 1
                },
                where: {
                    subject: data.field.subject
                }
            })
            return false;
        });
        document.getElementById('resetBtn').addEventListener('click', function () {
            // 重新加载表格，不带任何过滤条件
            table.reload('email-table', {
                where: {}, // 清除过滤条件
                page: {curr: 1} // 重新从第一页开始
            });
        });
        window.add = function () {
            layer.open({
                type: 2,
                title: '邮件新增',
                shade: 0.1,
                area: ['100%', '100%'],
                content: 'email-add'
            });
        }

        window.edit = function (obj) {
            window.state = obj.data.status;
            layer.open({
                type: 2,
                title: '邮件修改',
                shade: 0.1,
                shadeClose: true,
                area: ['100%', '100%'],
                content: 'email-edit',
                success: function (layero, index) {
                    if (obj.data.status !== 0) {
                        layer.msg("邮件正在发送或已发送，编辑无效", {icon: 0, time: 5000})
                    }
                    // 数据回显
                    let body = layer.getChildFrame('body', index)
                    let data = obj.data;
                    window.id = data.id
                    window.nowGroupId = data.groupId
                    window.nowChannelId = data.channelId
                    window.nowArticleId = data.articleId
                    body.find("input[name=subject]").val(data.subject)
                    if (data.emailAttachment !== "" && data.emailAttachment !== null) {
                        const fileName = data.emailAttachment.split('/').pop().split('_').slice(1).join('_');
                        // 显示文件名和图标
                        body.find('#file_p').html(
                            `${fileName}
                            <a href="${baseURL}${data.emailAttachment}" download="${fileName}" style="margin-left: 10px; color: #1e9fff;">
                            点击下载查看附件
                            </a>`
                        );
                        body.find('#removeAttachment').show();
                        body.find("input[name=emailAttachment]").val(data.emailAttachment)
                    }
                }
            })
        }
        window.remove = function (obj) {
            layer.confirm('确定要删除该邮件吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let status = obj.data.status;
                if (!(status === 0 || (status === 3 && (obj.data.failNum === 0 || obj.data.retry >= 3)))) {
                    layer.msg("邮件发送操作未完成，不能删除", {icon: 0, time: 2000})
                    return
                }

                let loading = layer.load();
                $.ajax({
                    url: baseURL + 'cms/email/delete/' + obj.data['id'],
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        table.reload('email-table', {where: {}, page: {curr: 1}});
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 2000
                            }, function () {

                            });
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 2000
                            });
                        }
                    },
                    error: function () {
                        layer.close(loading);
                        layer.msg("请求失败", {
                            icon: 2,
                            time: 2000
                        });
                    }
                });
            })
        }
        window.refresh = function () {
            table.reload('email-table');
        }

        let sendEmail = null;
        //发送邮件
        window.sending = function (obj) {
            layer.confirm('确定要发送邮件吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index); //关闭弹框
                if (obj.data.status !== 0) {
                    layer.msg("邮件已发送或正在发送中", {icon: 0, time: 2000})
                    return
                }
                let loading = layer.load();
                $.ajax({
                    url: baseURL + 'cms/email/sending',
                    data: {
                        id: obj.data.id,
                        sendTime: sendTime == null ? util.toDateString(Date.parse(new Date()), 'yyyy-MM-dd HH:mm:ss') : sendTime
                    },
                    type: 'post',
                    success: function (result) {
                        table.reload('email-table', {where: {}, page: {curr: 1}});
                        layer.close(loading);
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 2000
                            })
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 2000
                            });
                        }
                    },
                    error: function () {
                        layer.close(loading);
                        layer.msg("发送失败", {
                            icon: 2,
                            time: 2000
                        });
                    }
                })
            })
        }
        //定时发送
        let scheduleSendOpen;
        window.scheduleSend = function (obj) {
            if (obj.data.status !== 0) {
                layer.msg("邮件已发送或正在发送中", {icon: 0, time: 2000})
                return
            }
            sendEmail = obj
            scheduleSendOpen = layer.open({
                type: 1,
                title: '发送时间',
                shade: 0.1,
                area: ['450px', '200px'],
                content: $('#ID-test-layer-wrapper'),
            });
        }
        laydate.render({
            elem: '#ID-laydate-type-datetime',
            type: 'datetime',
            fullPanel: true,
        });
        let sendTime = null;
        form.on('submit(check-save)', function (data) {
            if (!data.field.sendDate) {
                layer.msg("请填写发送时间！", {icon: 2, time: 1500});
                return false;
            } else {
                const time = new Date(data.field.sendDate);
                const currentTime = new Date();
                currentTime.setMinutes(currentTime.getMinutes() + 1);
                if (time <= currentTime) {
                    layer.msg("定时发布时间必须大于当前时间一分钟！", {icon: 2, time: 1500});
                    return false;
                }
            }
            sendTime = data.field.sendDate
            window.sending(sendEmail)
            layer.close(scheduleSendOpen)
            return false;
        })
        //查看邮件成功日志
        window.viewSuccess = function (obj) {
            window.emailObjData = obj.data
            window.logStatus = 1;
            layer.open({
                type: 2,
                title: '邮件成功日志',
                shade: 0.1,
                area: ['100%', '100%'],
                content: 'email-log'
            });
        }

        //查看邮件失败日志
        window.viewFail = function (obj) {
            console.log(obj.data)
            window.emailObjData = obj.data
            window.logStatus = 0;
            layer.open({
                type: 2,
                title: '邮件失败日志',
                shade: 0.1,
                area: ['100%', '100%'],
                content: 'email-log',
                // success: function (layero, index) {
                //     let body = layer.getChildFrame('body', index)
                //     let data = obj.data;
                //     body.find("#resend").show()
                // }
            });
        }
    })
</script>
</body>
</html>
